package cn.tedu.tmall.admin.content.dao.repository.impl;

import cn.tedu.tmall.admin.content.dao.mapper.ArticleDetailMapper;
import cn.tedu.tmall.admin.content.dao.mapper.ArticleMapper;
import cn.tedu.tmall.admin.content.dao.repository.IArticleRepository;
import cn.tedu.tmall.admin.content.pojo.po.ArticleDetailPO;
import cn.tedu.tmall.admin.content.pojo.po.ArticlePO;
import cn.tedu.tmall.common.pojo.vo.PageData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 数据操作层-文章接口实现类
 */
@Slf4j
@Repository
public class ArticleRepository implements IArticleRepository {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleDetailMapper articleDetailMapper;

    @Override
    public Integer countArticleByTitle(String title) {
        QueryWrapper<ArticlePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",title);
        return articleMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer saveArticle(ArticlePO articlePO) {
        return articleMapper.insert(articlePO);
    }

    @Override
    public Integer saveArticleDetail(ArticleDetailPO articleDetailPO) {
        return articleDetailMapper.insert(articleDetailPO);
    }

    @Override
    public PageData<ArticlePO> selectList(Long categoryId, Integer pageNum, Integer pageSize) {
        QueryWrapper<ArticlePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id",categoryId);
        //articleMapper.page mybatis-plus 相关的可以提供分页功能 但是有点繁琐
        //通过mybaits动态sql 也能分页
        //使用pagehelper分页 拦截sql
        //有的公司是自己写分页
        PageHelper.startPage(pageNum, pageSize);
        List<ArticlePO> articlePOS = articleMapper.selectList(queryWrapper);
        //把通过pageHelper分页的数据PageInfo转化为自定义的PageData
        PageInfo<ArticlePO> pageInfo = new PageInfo<>(articlePOS);
        log.debug("分页后的数据：{}",pageInfo);
        PageData<ArticlePO> pageData = new PageData<>();
        BeanUtils.copyProperties(pageInfo,pageData);
        return pageData;
    }

    @Override
    public ArticlePO selectBasicInfo(Long articleId) {
        return articleMapper.selectById(articleId);
    }

    @Override
    public ArticleDetailPO selectDetail(Long articleId) {
        QueryWrapper<ArticleDetailPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id",articleId);
        return articleDetailMapper.selectOne(queryWrapper);
    }
}
